import React, { PureComponent, Fragment } from 'react';
import {
  Form,
  Input,
  Select,
  Modal,
  Radio, Icon, Upload, DatePicker,
  Drawer, Button,
} from 'antd';
import { phone, email } from '@/utils/regular';
import { connect } from 'dva';

const FormItem = Form.Item;
import moment from 'moment';

const RadioGroup = Radio.Group;


@connect(({ packing }) => ({
  packing,
}))
@Form.create()
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      appImg: [],
      appReport: [],
      pcImg: [],
      pcReport: [],
      appReportStr: '',
      pcReportStr: '',
    };
    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  onRemoveIcon = (e, type) => {
    console.log(this.state);
    const { iconList } = this.state;
    console.log(iconList);
    let dataArr = JSON.parse(JSON.stringify(iconList));
    dataArr.map((item, index) => {
      if (item.uid === e.uid) {
        dataArr.splice(index, 1);
      }
    });
    this.setState({
      iconList: dataArr,
    });
  };
  handleChange = (type, info) => {
    const { appReport, pcReport } = this.state;
    let logoList = info;
    logoList = logoList.map((file) => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });

    logoList = logoList.filter((file) => {
      if (file.response) {
        return file.response.status === 'success';
      }
      return true;
    });
    if (type === 'appImg') {
      this.setState({ appImg: logoList });
    } else if (type === 'appReport') {
      this.setState({ appReport: logoList });
    } else if (type === 'pcImg') {
      this.setState({ pcImg: logoList });
    } else if (type === 'pcReport') {
      this.setState({ pcReport: logoList });
    }
  };
  newForm = (componentsData) => {
    let originFile = componentsData.file;
    const formData = new FormData();
    formData.append('multipartFile', originFile);
    formData.append('name', originFile.name);
    formData.append('uid', originFile.uid);
    return formData;
  };
  appImgRequest = (componentsData) => {
    let _this = this;
    const { dispatch, form } = this.props;
    dispatch({
      type: 'global/upload',
      payload: this.newForm(componentsData),
      callback(res) {
        if (res.code === 200) {
          let obj = {
            ...res.msg,
          };
          form.setFieldsValue({
            appImg: res.msg.url,
          });
          _this.handleChange('appImg', [obj]);
        }
      },
    });
  };
  appReportRequest = (componentsData) => {
    let _this = this;
    const { dispatch, form } = this.props;
    dispatch({
      type: 'global/upload',
      payload: this.newForm(componentsData),
      callback(res) {
        if (res.code === 200) {
          let obj = {
            ...res.msg,
          };
          form.setFieldsValue({
            appReport: res.msg.url,
          });
          _this.handleChange('appReport', [obj]);
        }
      },
    });
  };
  pcImgRequest = (componentsData) => {
    let _this = this;
    const { dispatch, form } = this.props;
    dispatch({
      type: 'global/upload',
      payload: this.newForm(componentsData),
      callback(res) {
        if (res.code === 200) {
          let obj = {
            ...res.msg,
          };
          form.setFieldsValue({
            pcImg: res.msg.url,
          });
          _this.handleChange('pcImg', [obj]);
        }
      },
    });
  };
  pcReportRequest = (componentsData) => {
    let _this = this;
    const { dispatch, form } = this.props;
    dispatch({
      type: 'global/upload',
      payload: this.newForm(componentsData),
      callback(res) {
        if (res.code === 200) {
          let obj = {
            ...res.msg,
          };
          form.setFieldsValue({
            pcReport: res.msg.url,
          });
          _this.handleChange('pcReport', [obj]);
        }
      },
    });
  };
  // 表单
  renderContent = () => {
    const { form, values } = this.props;
    const { appImg, appReport, pcImg, pcReport } = this.state;
    let config = {
      action: `/img/upload`,
      multiple: false,
      showUploadList: { showPreviewIcon: true, showRemoveIcon: false },
      listType: 'picture-card',
      className: 'upload-list-inline',
    };
    const appImgProps = {
      onRemove: e => this.onRemoveIcon(e, 'appImg'),
      customRequest: this.appImgRequest,
      ...config,
    };
    const appReportProps = {
      onRemove: (e) => this.onRemoveIcon(e, 'appReport'),
      customRequest: this.appReportRequest,
      ...config,
    };

    const pcImgProps = {
      onRemove: (e) => this.onRemoveIcon(e, 'pcImg'),
      customRequest: this.pcImgRequest,
      ...config,
    };
    const pcReportProps = {
      onRemove: (e) => this.onRemoveIcon(e, 'pcReport'),
      customRequest: this.pcReportRequest,
      ...config,

    };
    return [
      <FormItem key="title" {...this.formLayout} label="标题">
        {form.getFieldDecorator('title', {
          rules: [{ required: true, message: '请输入标题！' }],
          initialValue: values.title,
        })(<Input placeholder="请输入标题"/>)}
      </FormItem>,
      <FormItem key="appImg" {...this.formLayout} label="app头图">
        {
          appImg.length > 0 ?
            form.getFieldDecorator('appImg', {
              rules: [{ required: true, message: '请上传app头图！' }],
              initialValue: values.appImg,
            })(
              <Upload {...appImgProps} fileList={appImg}>
                <Icon type="upload"/> 上传
              </Upload>,
            ) :
            form.getFieldDecorator('appImg', {
              rules: [{ required: true, message: '请上传app头图！' }],
              initialValue: values.appImg,
            })(
              <Upload {...appImgProps} fileList={
                values.appImg ? [{
                  name: values.appImg,
                  uid: 1,
                  url: values.appImg,
                }] : []
              }>
                <Icon type="upload"/> 上传
              </Upload>,
            )
        }
      </FormItem>,
      <FormItem key="appReport" {...this.formLayout} label="app运营报告">
        {
          appReport.length > 0 ?
            form.getFieldDecorator('appReport', {
              rules: [{ required: true, message: '请上传app头图！' }],
              initialValue: values.appReport,
            })(
              <Upload {...appReportProps} fileList={appReport}>
                <Icon type="upload"/> 上传
              </Upload>,
            ) :
            form.getFieldDecorator('appReport', {
              rules: [{ required: true, message: '请上传app头图！' }],
              initialValue: values.appReport,
            })(
              <Upload {...appReportProps} fileList={
                values.appReport ? [{
                  name: values.appReport,
                  uid: 1,
                  url: values.appReport,
                }] : []
              }>
                <Icon type="upload"/> 上传
              </Upload>,
            )}
      </FormItem>,
      <FormItem key="pcImg" {...this.formLayout} label="pc头图">
        {
          pcImg.length > 0 ?
            form.getFieldDecorator('pcImg', {
              rules: [{ required: true, message: '请上传app头图！' }],
              initialValue: values.pcImg,
            })(
              <Upload {...pcImgProps} fileList={pcImg}>
                <Icon type="upload"/> 上传
              </Upload>,
            ) :
            form.getFieldDecorator('pcImg', {
              rules: [{ required: true, message: '请上传app头图！' }],
              initialValue: values.pcImg,
            })(
              <Upload {...pcImgProps} fileList={
                values.pcImg ? [{
                  name: values.pcImg,
                  uid: 1,
                  url: values.pcImg,
                }] : []
              }>
                <Icon type="upload"/> 上传
              </Upload>,
            )}
      </FormItem>,
      <FormItem key="pcReport" {...this.formLayout} label="pc运营报告">
        {
          pcReport.length > 0 ?
            form.getFieldDecorator('pcReport', {
              rules: [{ required: true, message: '请上传pc运营报告！' }],
              initialValue: values.pcReport,
            })(
              <Upload {...pcReportProps} fileList={pcReport}>
                <Icon type="upload"/> 上传
              </Upload>,
            ) :
            form.getFieldDecorator('pcReport', {
              rules: [{ required: true, message: '请上传pc运营报告！' }],
              initialValue: values.pcReport,
            })(
              <Upload {...pcReportProps} fileList={
                values.pcReport ? [{
                  name: values.pcReport,
                  uid: 1,
                  url: values.pcReport,
                }] : []
              }>
                <Icon type="upload"/> 上传
              </Upload>,
            )}
      </FormItem>,
      <FormItem key="status" {...this.formLayout} label="状态">
        {form.getFieldDecorator('status', {
          rules: [{ required: true, message: '请选择状态！' }],
          initialValue: values.status || 1,
        })(
          <RadioGroup>
            <Radio value={1}>启用</Radio>
            <Radio value={2}>停用</Radio>
          </RadioGroup>,
        )}
      </FormItem>,


      <FormItem key="publishTime" {...this.formLayout} label="发布时间">
        {form.getFieldDecorator('publishTime', {
          rules: [{ required: true, message: '请选择发布时间！' }],
          initialValue: moment(values.startTime),
        })(<DatePicker placeholder="请选择发布时间" style={{ width: '100%' }}/>)}
      </FormItem>,

    ];
  };

  //弹窗
  render() {
    const { updateModalVisible, handleUpdateModalVisible, modalVisible } = this.props;

    const handleNext = () => {
      const { form, values, handleUpdate, handleAdd, modalVisible } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        const formVals = { ...values, ...fieldsValue };
        formVals.publishTime = fieldsValue.publishTime ? moment(fieldsValue.publishTime).format('YYYY-MM-DD') : '';
        if (modalVisible) {
          handleAdd(formVals);
        } else {
          handleUpdate(formVals);
        }
        this.setState({
          appImg: [],
          appReport: [],
          pcImg: [],
          pcReport: [],
        });
      });
    };
    const onClose = () => {
      handleUpdateModalVisible(false, []);
      this.setState({
        appImg: [],
        appReport: [],
        pcImg: [],
        pcReport: [],
      });
    };
    return (
      <Drawer
        width={700}
        destroyOnClose
        title={modalVisible ? '新增运营报告' : '修改运营报告'}
        visible={updateModalVisible}
        onOk={handleNext}
        onClose={onClose}
      >
        {this.renderContent()}
        <div
          style={{
            position: 'absolute',
            left: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}
        >
          <Button onClick={() => handleUpdateModalVisible(false, [])} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button onClick={handleNext} type="primary">
            提交
          </Button>
        </div>
      </Drawer>
    );
  }
}

export default UpdateForm;
